var express = require('express');
//导入Node.js的Path模块
var path = require('path');
//导入Express的Cookie模块
var cookieParser = require('cookie-parser');
//导入日志模块
var logger = require('morgan');

//导入 swagger-ui-express模块
const swaggerUi = require("swagger-ui-express");
//导入swagger-jsdoc模块
const swaggerJsdoc = require("swagger-jsdoc");
// 导入初始化数据库中间件
const initSqliteDB = require("./controller/init");
const uploader = require("./common/uploader");

//自定义路由
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var cartsRouter = require('./routes/carts');
var goodsRouter = require('./routes/goods');
var review = require('./routes/review');
var ordersRouter = require('./routes/orders');
const config = require("./common/config");
const util = require("./common/util");

// 导入Session模块
const session = require("express-session");
// 导入Session存储支持模块SQLite
const SQLiteStore = require("connect-sqlite3")(session);

var app = express();

//自己的中间件
app.use(initSqliteDB());
/**
 * Express中的Session支持
 * 1. npm install express-sesion connect-sqlite3
 * 2. 导入模块
 * 3. 使用Session中间件
 * 4. Session存储：SQLiteStore
 */
app.use(
  session({
    secret: config.salt, //session的salt
    resave: false, //session工作方式：session是否重新保存
    saveUninitialized: false, //session工作方式：未初始化的session是否保存
    cookie: { maxAge: 7 * 24 * 60 * 60 * 1000 }, // sessionID在客户端cookie中保存1周
    store: new SQLiteStore({
      dir: "./data",
      db: "market.db",
    }),
  })
);

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/goods', goodsRouter);
app.use('/carts', cartsRouter);
app.use('/review',review);

app.use('/orders', ordersRouter);

// app.use((req, res, next) => {
//   res.header('Access-Control-Allow-Origin', 'http://localhost:5006'); // 本地开发端口
//   res.header('Access-Control-Allow-Credentials', true);
//   res.header('Access-Control-Allow-Headers', 'Content-Type');
//   next();
// });

app.post('/upfile', uploader.upload.single('imgfile'), function(req, res){
    if (!req.file) {
      return res.status(400).send('未接收到文件');
    }
    res.send(util.FormatJSONData(201, '上传成功', req.file.filename));
  });

app.use(express.static(path.join(__dirname, 'public')));

//swagger中间件
const options = {
    definition:{
        openapi:"3.0.0",
        info:{
            title:"校园二手交易平台接口",
            version:"1.0.0"
        },
    },
    //这个路由下都支持这样的一个生成
    apis:[path.join(__dirname,"./routes/*.js")]
};


const openapiSpecification = swaggerJsdoc(options);
app.use("/dev-api",swaggerUi.serve,swaggerUi.setup(openapiSpecification));



/**
 * Express中的Session支持
 * 1. npm install express-sesion connect-sqlite3
 * 2. 导入模块
 * 3. 使用Session中间件
 * 4. Session存储：SQLiteStore
 */
app.use(
    session({
      secret: config.salt, //session的salt
      resave: false, //session工作方式：session是否重新保存
      saveUninitialized: false, //session工作方式：未初始化的session是否保存
      cookie: { maxAge: 7 * 24 * 60 * 60 * 1000 }, // sessionID在客户端cookie中保存1周
      store: new SQLiteStore({
        dir: "./data",
        db: "market.db",
      }),
    })
  );


module.exports = app;
